package utils

import (
	"net/url"
	"path/filepath"
	"regexp"
	"strings"
)

// 解析相对URL为绝对URL
func resolveURL(base *url.URL, href string) string {
	// 忽略锚点链接和javascript
	if strings.HasPrefix(href, "#") || strings.HasPrefix(href, "javascript:") {
		return ""
	}

	relURL, err := url.Parse(href)
	if err != nil {
		return ""
	}

	absURL := base.ResolveReference(relURL)
	return absURL.String()
}

// 从CSS文本中提取URL
func extractCSSURLs(cssText string, baseURL *url.URL) []string {
	urls := make([]string, 0)
	re := regexp.MustCompile(`url\(['"]?([^'")]+)['"]?\)`)
	matches := re.FindAllStringSubmatch(cssText, -1)

	for _, match := range matches {
		if len(match) > 1 {
			absURL := resolveURL(baseURL, match[1])
			if absURL != "" {
				urls = append(urls, absURL)
			}
		}
	}

	return urls
}

// 从URL获取相对路径
func getPathFromURL(parsedURL *url.URL) string {
	path := parsedURL.Path
	if path == "" || path == "/" || path == "//" {
		return ""
	}

	// 移除开头的斜杠
	path = strings.TrimPrefix(path, "/")

	// 获取目录部分
	dir := filepath.Dir(path)
	if dir == "." {
		return ""
	}

	return dir
}
